package com.example.candiates.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.candiates.domain.InterviewCandidates;
import com.example.candiates.domain.InterviewQuestion;
import com.example.candiates.domain.DigitalInterviewer;
import com.example.candiates.domain.InterviewSchedule;
import com.example.candiates.domain.InterviewAnswer;
import com.example.candiates.mapper.InterviewCandidatesMapper;
import com.example.candiates.mapper.CandidateInterviewScheduleMapper;
import com.example.candiates.mapper.InterviewAnswerMapper;
import com.example.candiates.service.CandidateService;
import com.example.candiates.service.InterviewQuestionService;
import com.example.candiates.service.DigitalInterviewerService;
import com.example.candiates.dto.InterviewScheduleDTO;
import com.example.candiates.domain.QuestionSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class CandidateServiceImpl implements CandidateService {
    
    private static final Logger log = LoggerFactory.getLogger(CandidateServiceImpl.class);
    
    @Autowired
    private InterviewCandidatesMapper interviewCandidatesMapper;
    
    @Autowired
    private CandidateInterviewScheduleMapper interviewScheduleMapper;
    
    @Autowired
    private InterviewAnswerMapper interviewAnswerMapper;
    
    @Autowired
    private InterviewQuestionService interviewQuestionService;
    
    @Autowired
    private DigitalInterviewerService digitalInterviewerService;
    
    @Override
    public List<InterviewCandidates> getByPhone(String phone) {
        LambdaQueryWrapper<InterviewCandidates> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InterviewCandidates::getPhone, phone);
        return interviewCandidatesMapper.selectList(wrapper);
    }
    
    @Override
    public InterviewCandidates getInterviewSchedule(Integer candidateId) {
        try {
            return interviewCandidatesMapper.selectById(candidateId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public Map<String, Object> getInterviewDetails(Integer candidateId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("开始获取面试详情，候选人ID: {}", candidateId);
            
            // 1. 获取候选人信息
            InterviewCandidates candidate = interviewCandidatesMapper.selectById(candidateId);
            if (candidate == null) {
                log.warn("未找到候选人信息，候选人ID: {}", candidateId);
                return result;
            }
            log.info("获取到候选人信息: {}", candidate);
            result.put("candidateInfo", candidate);
            
            // 2. 获取所有面试安排
            List<InterviewSchedule> allSchedules = interviewScheduleMapper.getAllSchedules();
            log.info("所有面试安排: {}", allSchedules);
            
            // 3. 获取最新的面试安排
            InterviewSchedule schedule = interviewScheduleMapper.getLatestScheduleByCandidateId(candidateId);
            if (schedule == null) {
                log.warn("未找到面试安排，候选人ID: {}", candidateId);
                return result;
            }
            
            log.info("获取到面试安排: {}", schedule);
            result.put("schedule", schedule);
            
            // 查询数字人面试官信息
            if (schedule.getDigitalInterviewerId() != null) {
                DigitalInterviewer interviewer = digitalInterviewerService.getById(schedule.getDigitalInterviewerId());
                if (interviewer != null) {
                    Map<String, Object> interviewerInfo = new HashMap<>();
                    interviewerInfo.put("id", interviewer.getId());
                    interviewerInfo.put("name", interviewer.getName());
                    interviewerInfo.put("avatar", interviewer.getAvatar());
                    result.put("interviewer", interviewerInfo);
                }
            }
            
            // 4. 获取面试题目
            String questionSetIds = schedule.getQuestionSetIds();
            log.info("面试安排的题目集IDs: {}", questionSetIds);
            
            if (questionSetIds != null && !questionSetIds.isEmpty()) {
                try {
                    // 解析 JSON 数组
                    List<Integer> setIds = new com.fasterxml.jackson.databind.ObjectMapper()
                        .readValue(questionSetIds, new com.fasterxml.jackson.core.type.TypeReference<List<Integer>>() {});
                    
                    log.info("解析后的题目集IDs: {}", setIds);
                    
                    List<InterviewQuestion> questions = interviewScheduleMapper.getQuestionsBySetIds(setIds);
                    if (questions != null && !questions.isEmpty()) {
                        log.info("获取到题目数量: {}", questions.size());
                        result.put("questions", questions);
                    } else {
                        log.warn("未找到题目，题目集IDs: {}", questionSetIds);
                    }
                } catch (Exception e) {
                    log.error("解析题目集ID失败: {}", questionSetIds, e);
                }
            } else {
                log.warn("面试安排中没有题目集ID");
            }
            
            if (result.isEmpty()) {
                log.warn("未找到任何面试详情，候选人ID: {}", candidateId);
            } else {
                log.info("成功获取面试详情: {}", result);
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取面试详情失败: {}", e.getMessage(), e);
            return result;
        }
    }
    
    @Override
    public boolean startInterview(Integer candidateId) {
        try {
            // 获取候选人信息
            InterviewCandidates candidate = interviewCandidatesMapper.selectById(candidateId);
            if (candidate == null) {
                System.err.println("未找到候选人信息，ID: " + candidateId);
                return false;
            }
            
            // 检查面试状态
            if (candidate.getInterviewStatus() != 1) {
                System.err.println("当前面试状态不允许开始面试，状态: " + candidate.getInterviewStatus());
                return false;
            }
            
            // 更新面试状态为面试中
            candidate.setInterviewStatus(2);
            int rows = interviewCandidatesMapper.updateById(candidate);
            
            return rows > 0;
        } catch (Exception e) {
            System.err.println("开始面试失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean submitAnswer(Integer candidateId, Integer questionId, String answer) {
        try {
            // 获取候选人信息
            InterviewCandidates candidate = interviewCandidatesMapper.selectById(candidateId);
            if (candidate == null) {
                System.err.println("未找到候选人信息，ID: " + candidateId);
                return false;
            }

            // 检查面试状态
            if (candidate.getInterviewStatus() != 2) { // 2表示面试中
                System.err.println("面试状态不正确，当前状态: " + candidate.getInterviewStatus());
                return false;
            }

            // 保存答案
            InterviewAnswer interviewAnswer = new InterviewAnswer();
            interviewAnswer.setCandidateId(candidateId);
            interviewAnswer.setQuestionId(questionId);
            interviewAnswer.setAnswer(answer);
            interviewAnswer.setCreateTime(new Date());

            int result = interviewAnswerMapper.insert(interviewAnswer);
            return result > 0;
        } catch (Exception e) {
            System.err.println("提交答案失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean completeInterview(Integer candidateId) {
        try {
            // 获取候选人信息
            InterviewCandidates candidate = interviewCandidatesMapper.selectById(candidateId);
            if (candidate == null) {
                System.err.println("未找到候选人信息，ID: " + candidateId);
                return false;
            }

            // 检查面试状态
            if (candidate.getInterviewStatus() != 2) { // 2表示面试中
                System.err.println("面试状态不正确，当前状态: " + candidate.getInterviewStatus());
                return false;
            }

            // 更新面试状态为面试完成（3）
            candidate.setInterviewStatus(3);
            candidate.setUpdatedAt(new Date());

            int result = interviewCandidatesMapper.updateById(candidate);
            return result > 0;
        } catch (Exception e) {
            System.err.println("完成面试失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public InterviewScheduleDTO getFullInterviewDetailByPhone(String phone) {
        InterviewScheduleDTO dto = interviewScheduleMapper.getFullInterviewDetailByPhone(phone);
        if (dto != null && dto.getSchedule() != null && dto.getSchedule().getQuestionSetIds() != null) {
            // 解析JSON数组
            List<Integer> setIds = new ArrayList<>();
            try {
                setIds = new com.fasterxml.jackson.databind.ObjectMapper()
                        .readValue(dto.getSchedule().getQuestionSetIds(), new com.fasterxml.jackson.core.type.TypeReference<List<Integer>>() {});
            } catch (Exception e) {
                log.error("解析题目集ID失败: {}", dto.getSchedule().getQuestionSetIds(), e);
            }
            if (!setIds.isEmpty()) {
                // 查询题目集
                List<QuestionSet> sets = new ArrayList<>();
                for (Integer setId : setIds) {
                    // 这里假设有 questionSetMapper，实际请替换为你的mapper/service
                    // sets.add(questionSetMapper.selectById(setId));
                }
                dto.setQuestionSets(sets);
                // 查询题目
                List<InterviewQuestion> questions = interviewScheduleMapper.getQuestionsBySetIds(setIds);
                dto.setQuestions(questions);
            }
        }
        return dto;
    }
} 